import {
  wxLogin,
  wxRefreshToken
} from '../../../../api/index'
const AuthStepType = {
  ONE: 1,
  TWO: 2,
  THREE: 3,
};

Component({
  options: {
    multipleSlots: true,
  },
  properties: {
    currAuthStep: {
      type: Number,
      value: AuthStepType.ONE,
    },
    userInfo: {
      type: Object,
      value: {},
    },
    isNeedGetUserInfo: {
      type: Boolean,
      value: false,
    },
  },
  data: {
    defaultAvatarUrl: '/image/mine-av.png',
    AuthStepType,
  },
  methods: {
    // 封装存储逻辑  
    async setStorageItem(key, data) {
      try {
        await wx.setStorage({
          key,
          data,
          success(res) {
            console.log(res, 'cun')
            console.log(`${key} 存储成功`, res);
          },
          fail(err) {
            console.error(`${key} 存储失败`, err);
          }
        });
      } catch (error) {
        console.error(`存储 ${key} 时发生错误`, error);
      }
    },

    // 登录函数  
    async gotoUserEditPage() {
      try {
        const res = await new Promise((resolve, reject) => {
          wx.login({
            success: (loginRes) => {
              resolve(loginRes);
            },
            fail: (err) => {
              console.error('登录失败', err);
              reject(err);
            }
          });
        });

        const code = res.code;
        const loginRes = await wxLogin({
          code
        });
        const {
          accessToken,
          refreshToken
        } = loginRes.data;

        await setStorageItem('user_token', accessToken);
        await setStorageItem('user_refreshToken', refreshToken);

        wx.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 2000
        });
        this.triggerEvent('gotoUserEditPage');
      } catch (error) {
        console.error('登录过程中发生错误', error);
      }
    },
    // gotoUserEditPage()
  },
});